"""
插槽（Slots）管理模块
用于管理课后服务预定所需的各种信息槽位
"""
from typing import Optional, List, Dict, Any
from dataclasses import dataclass, field
from enum import Enum


class IntentType(Enum):
    """意图类型"""
    BOOK = "book"  # 预定
    CANCEL = "cancel"  # 取消
    QUERY = "query"  # 查询
    LIST_ALL = "list_all"  # 查看所有
    UNKNOWN = "unknown"  # 未知


class ServiceType(Enum):
    """课后服务类型"""
    HOMEWORK_TUTORING = "作业辅导"
    SUBJECT_TUTORING = "学科辅导"
    INTEREST_CLASS = "兴趣班"
    SPORTS_ACTIVITY = "体育活动"
    ART_CLASS = "艺术课程"


@dataclass
class BookingSlots:
    """预定插槽类 - 用于收集预定所需的所有信息"""
    
    # 意图
    intent: Optional[IntentType] = None
    
    # 学生信息
    student_name: Optional[str] = None
    
    # 服务信息
    service_type: Optional[ServiceType] = None
    
    # 时间信息
    date: Optional[str] = None  # 格式: YYYY-MM-DD
    time_slot: Optional[str] = None  # 格式: HH:MM-HH:MM
    
    # 其他信息
    teacher_preference: Optional[str] = None  # 教师偏好
    notes: Optional[str] = None  # 备注
    
    # 查询/取消时使用
    booking_id: Optional[str] = None
    
    # 元信息
    missing_slots: List[str] = field(default_factory=list)
    confirmed: bool = False
    
    def get_required_slots(self) -> List[str]:
        """根据意图获取必需的插槽"""
        if self.intent == IntentType.BOOK:
            return ["student_name", "service_type", "date", "time_slot"]
        elif self.intent == IntentType.CANCEL:
            return ["booking_id"]
        elif self.intent == IntentType.QUERY:
            return ["student_name"]
        elif self.intent == IntentType.LIST_ALL:
            return []
        return []
    
    def get_missing_slots(self) -> List[str]:
        """获取缺失的必需插槽"""
        required = self.get_required_slots()
        missing = []
        
        for slot_name in required:
            value = getattr(self, slot_name, None)
            if value is None:
                missing.append(slot_name)
        
        return missing
    
    def is_complete(self) -> bool:
        """检查所有必需插槽是否已填充"""
        return len(self.get_missing_slots()) == 0
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            "intent": self.intent.value if self.intent else None,
            "student_name": self.student_name,
            "service_type": self.service_type.value if self.service_type else None,
            "date": self.date,
            "time_slot": self.time_slot,
            "teacher_preference": self.teacher_preference,
            "notes": self.notes,
            "booking_id": self.booking_id,
            "confirmed": self.confirmed
        }
    
    def get_slot_prompt_message(self, slot_name: str) -> str:
        """获取询问特定插槽的提示信息"""
        prompts = {
            "student_name": "请问学生的姓名是？",
            "service_type": f"请选择课后服务类型：\n" + 
                          "\n".join([f"{i+1}. {st.value}" 
                                    for i, st in enumerate(ServiceType)]),
            "date": "请问您要预定哪一天的服务？（格式：2024-01-01）",
            "time_slot": "请问您要预定的时间段？（格式：14:00-16:00）",
            "teacher_preference": "您有偏好的老师吗？（可选）",
            "booking_id": "请提供预定编号",
        }
        return prompts.get(slot_name, f"请提供 {slot_name}")
    
    def __str__(self) -> str:
        """字符串表示"""
        return f"""
预定信息：
- 意图: {self.intent.value if self.intent else '未知'}
- 学生姓名: {self.student_name or '未填写'}
- 服务类型: {self.service_type.value if self.service_type else '未选择'}
- 日期: {self.date or '未选择'}
- 时间段: {self.time_slot or '未选择'}
- 教师偏好: {self.teacher_preference or '无'}
- 备注: {self.notes or '无'}
- 是否完整: {'是' if self.is_complete() else '否'}
        """.strip()


class SlotFiller:
    """插槽填充器 - 负责从用户输入中提取和填充插槽信息"""
    
    @staticmethod
    def extract_intent(user_input: str) -> IntentType:
        """从用户输入中提取意图"""
        user_input_lower = user_input.lower()
        
        # 优先检查取消意图
        if any(word in user_input_lower for word in ["取消", "退订", "不要了", "删除预定", "退掉"]):
            return IntentType.CANCEL
        # 检查列表意图（在查询之前，更具体）
        elif any(word in user_input_lower for word in ["所有预定", "全部预定", "全部的预定", "所有的预定"]) or \
             ("查看" in user_input_lower and "所有" in user_input_lower):
            return IntentType.LIST_ALL
        # 检查查询意图
        elif any(word in user_input_lower for word in ["查询", "有哪些预定"]) or "我的预定" in user_input_lower:
            return IntentType.QUERY
        # 检查预定意图
        elif any(word in user_input_lower for word in ["想预定", "想预约", "预定", "预约", "报名", "想上"]):
            return IntentType.BOOK
        else:
            return IntentType.UNKNOWN
    
    @staticmethod
    def extract_service_type(user_input: str) -> Optional[ServiceType]:
        """从用户输入中提取服务类型"""
        user_input_lower = user_input.lower()
        
        for service in ServiceType:
            if service.value in user_input or service.name.lower() in user_input_lower:
                return service
        
        # 检查关键词
        keyword_mapping = {
            "作业": ServiceType.HOMEWORK_TUTORING,
            "辅导": ServiceType.SUBJECT_TUTORING,
            "兴趣": ServiceType.INTEREST_CLASS,
            "体育": ServiceType.SPORTS_ACTIVITY,
            "运动": ServiceType.SPORTS_ACTIVITY,
            "艺术": ServiceType.ART_CLASS,
            "绘画": ServiceType.ART_CLASS,
            "音乐": ServiceType.ART_CLASS,
        }
        
        for keyword, service in keyword_mapping.items():
            if keyword in user_input:
                return service
        
        return None
    
    @staticmethod
    def extract_student_name(user_input: str, slots: BookingSlots) -> Optional[str]:
        """从用户输入中提取学生姓名"""
        # 简单实现：如果是回答姓名的问题，直接返回输入
        if slots.intent and not slots.student_name:
            # 去除常见的前缀
            name = user_input.strip()
            for prefix in ["我叫", "我是", "学生是", "姓名是", "名字是"]:
                if name.startswith(prefix):
                    name = name[len(prefix):].strip()
            
            # 基本验证：2-4个字符
            if 2 <= len(name) <= 4 and name.replace(" ", "").isalnum():
                return name
        
        return None
